package com.yap.mvc;

import mvc.Uploads;
import com.yap.mvc.util.JsfUtil;
import com.yap.mvc.util.PaginationHelper;
import com.mvc.UploadsFacade;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletResponse;
import mvc.FileUploadController;
import org.primefaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named("uploadsController")
@SessionScoped
public class UploadsController implements Serializable {

    private Uploads current;
    private DataModel items = null;
    @EJB
    private com.mvc.UploadsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String destination = "/home/tadiwa/Uploads/";
    private UploadedFile file;
    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
    private String doc;
    private File myUpload;

    public UploadsController() {
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void transferfile(String fileName, InputStream in) {
        try {
            myUpload = new File(destination + fileName);
            OutputStream out = new FileOutputStream(myUpload);
            int reader = 0;
            byte[] bytes = new byte[(int) getFile().getSize()];
            while ((reader = in.read(bytes)) != -1) {
                out.write(bytes, 0, reader);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void upload() throws IOException {
        String extValidate;
        if (getFile() != null) {
            String ext = getFile().getFileName();
            if (ext != null) {
                extValidate = ext.substring(ext.indexOf(".") + 1);
            } else {
                extValidate = "null";
            }

            if (extValidate.equals("pdf") || (extValidate.equals("doc")) || (extValidate.equals("docx")) || (extValidate.equals("ppt")) || (extValidate.equals("xls")) || (extValidate.equals("xlsx")) || (extValidate.equals("csv"))) {
                try {
                    this.transferfile(getFile().getFileName(), getFile().getInputstream());
                } catch (IOException ex) {
                    log.error(ex.getMessage(), ex);
                    FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null, new FacesMessage("Error: ", "Upload Failed"));
                }
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Successfully uploaded", getFile().getFileName()));
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Error:", "Unsupported Format, use .pdf or .doc"));
            }
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Error:", "No Selected File"));
        }
    }

    public void downloadDoc() {
        try {
            File file = new File("/home/tadiwa/Uploads/" + getFile().getFileName());
            InputStream fis = new FileInputStream(file);
            byte[] buf = new byte[(int) (getFile().getSize())];
            int offset = 0;
            int numRead = 0;
            while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) {

                offset += numRead;

            }
            fis.close();
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + getFile().getFileName() + "");
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException ex) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Error:", "No File to download"));
        }
    }

    public Uploads getSelected() {
        if (current == null) {
            current = new Uploads();
            selectedItemIndex = -1;
        }
        return current;
    }

    private UploadsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Uploads) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Uploads();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            this.upload();            
            String actualFile = myUpload.getName();
            //actualFile = actualFile.replaceAll(destination, "");
            System.out.println(">> Path : "+actualFile);
            current.setDocument(actualFile);
            current.setUploadedby(Uploader.getUsername());
            current.setUploaddate(new Date(System.currentTimeMillis()));
            System.out.println(">> Path : "+actualFile);
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UploadsCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Uploads) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UploadsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Uploads) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UploadsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Uploads getUploads(java.lang.Integer id) {
        return ejbFacade.find(id);
    }
    
    public String prepareDownload() {
        current = (Uploads) getItems().getRowData();
        String root = destination;
        String fileName = current.getDocument();
        System.out.println(">> root :"+root+", fileNme : "+fileName);
         ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
         if(ctx != null) {
            try {
                ctx.redirect("/yapp/DownloadServlet?root="+root+"&fileName="+fileName);
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(UploadsController.class.getName()).log(Level.SEVERE, null, ex);
            }
         } else {
             JsfUtil.addErrorMessage("Failed to resolve faces context");
         }
        return "download";
    }
        
    @FacesConverter(forClass = Uploads.class)
    public static class UploadsControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UploadsController controller = (UploadsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "uploadsController");
            return controller.getUploads(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Uploads) {
                Uploads o = (Uploads) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Uploads.class.getName());
            }
        }

    }

}
